#import <stdlib.h>
#import "collaboration.h"
#import "listeningObject.h"
#import "eventListener.h"

@implementation ListeningObject

-(id) init
{
	if (![super init])
		return nil;
	
	listeners = [[NSMutableArray alloc] init];
	return self;
}

-(void) dealloc
{
	[listeners release];
	[super dealloc];
}

-(int) listenerPosition:(NSString*)name
{
	NSUInteger i,size;
	size = [listeners count];
	for (i=0; i<size; i++)
	{
		if ([[[listeners objectAtIndex:i] name] isEqualToString:name])
			return i;
	}
	
	return -1;
}

-(void) addEventListener:(id<EventListener>)ev
{
	int pos = [self listenerPosition:[ev name]];
	if (pos == -1) //no existe
	{
		[listeners addObject:ev];
	}
}

-(void) removeEventListener:(id<EventListener>)ev
{
	[self removeEventListenerWithName:[ev name]];
}

-(void) removeEventListenerWithName:(NSString*)name
{
	int pos = [self listenerPosition:name];
	if (pos != -1)
	{
		[listeners removeObjectAtIndex:pos];
	}
}

-(void) listen:(Event*)evt
{
	for (id<EventListener> e in listeners)
	{
		[e action:self event:evt];
	}
}

@end
